/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.unpack.file.utils;

import cn.ac.iie.unpack.file.global.GlobalParas;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

/**
 *
 * @author moli
 */
public class FileUntarAndMove {

    public static Logger LOG = Logger.getLogger(FileUntarAndMove.class);

    public List<String> unTar(File inputFile, File outputDir) throws FileNotFoundException, ArchiveException, Exception {
        LOG.info(String.format("Untaring %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));
        TarArchiveInputStream debInputStream = new TarArchiveInputStream(new FileInputStream(inputFile));
        
        TarArchiveEntry entry = null;
        
        File outputFile=null;
        List<String> untarfiles=new ArrayList<String>();
        while ((entry = debInputStream.getNextTarEntry()) != null) {
            String entryFileName = entry.getName();
            String entryFilePath ;
            entryFilePath = outputDir.getAbsolutePath() + File.separator + entryFileName;
            if(entryFileName.endsWith("log")){
                untarfiles.add(entryFilePath);
            }
            OutputStream os = null;        
        try{
            outputFile = new File(entryFilePath);
            if(!outputFile.getParentFile().exists()){
                outputFile.getParentFile().mkdirs();
                outputFile.createNewFile();
            }
            if(entryFileName.endsWith("/")){
                outputFile.mkdirs();
            }else if(!outputFile.isDirectory()){
                 os = new BufferedOutputStream(new FileOutputStream(outputFile));
                 byte[] buffer = new byte[1024];
                 int len = -1;
                 while ((len = debInputStream.read(buffer)) != -1) {
                     os.write(buffer, 0, len);
                }
            }
//            LOG.info(String.format("Creating output file %s.", outputFile.getAbsolutePath()));
//            if(outputFile.isDirectory()){
//                continue;
//            }
//            FileOutputStream outputFileStream;
//            outputFileStream = new FileOutputStream(outputFile);
//            IOUtils.copy(debInputStream, outputFileStream);
//            outputFileStream.close();
        }catch (Exception e){
            throw e;
        }finally {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            }     
        }
        debInputStream.close();
        return untarfiles;
    }
    
    
    
//    public File unTar(File inputFile, File outputDir) throws FileNotFoundException, ArchiveException, IOException {
//        LOG.info(String.format("Untaring %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));
//
//        InputStream is = new FileInputStream(inputFile);
//        TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
//        TarArchiveEntry entry = null;
//
//        File outputFile=null;
//        while ((entry = (TarArchiveEntry)debInputStream.getNextTarEntry()) != null) {
//            outputFile = new File(outputDir,entry.getName());
//            
//            LOG.info(String.format("Creating output file %s.", outputFile.getAbsolutePath()));
//            FileOutputStream outputFileStream;
//            outputFileStream = new FileOutputStream(outputFile);
//            IOUtils.copy(debInputStream, outputFileStream);
//            outputFileStream.close();
//            
//        }
//        debInputStream.close();
//        return outputFile;
//    }

    
    
    public void copy(File fromFile,String toDirPath) throws IOException{
        if(!fromFile.exists()){
            LOG.error(String.format("%s file does not exists.",fromFile.getAbsolutePath()));
            return;
        }
        File toDir=new File(toDirPath);
        if(!toDir.exists()){
            toDir.mkdir();
        }
        FileUtils.copyFileToDirectory(fromFile, toDir);
        LOG.info("copy file "+fromFile.getAbsolutePath()+" to dir "+toDirPath+" successfully.");
    }
    
    public void move(File fromFile,String toDirPath) throws IOException{
        if(!fromFile.exists()){
            LOG.error(String.format("%s file does not exists.",fromFile.getAbsolutePath()));
            return;
        }
        File toDir=new File(toDirPath);
        if(!toDir.exists()){
            toDir.mkdir();
        }
        FileUtils.copyFileToDirectory(fromFile, toDir);
        fromFile.delete();
        
        LOG.info("move file "+fromFile.getAbsolutePath()+" to dir "+toDirPath+" successfully.");
    }
    public void movefile(File fromFile,String toLongChun){
        if(!fromFile.exists()){
            LOG.error(String.format("%s file does not exists.",fromFile.getAbsolutePath()));
            return;
        }
        File longchun=new File(toLongChun);
        longchun.getParentFile().mkdirs();
        try {
            FileUtils.copyFile(fromFile, longchun);
        } catch (IOException ex) {
            LOG.error(ex.getStackTrace(),ex);
            LOG.error(String.format("%s to %s.",fromFile.getAbsolutePath(),toLongChun));
        }
        fromFile.delete();
        
        LOG.info("move file "+fromFile.getAbsolutePath()+" to file "+toLongChun+" successfully.");
    }
    
    public void delete(File fromFile,String toDirPath) throws IOException{
        if(!fromFile.exists()){
            LOG.error(String.format("%s file does not exists.",fromFile.getAbsolutePath()));
            return;
        }
        File toDir=new File(toDirPath);
        if(!toDir.exists()){
            toDir.mkdir();
        }

        fromFile.delete();
        
        LOG.info("delete file "+fromFile.getAbsolutePath()+" to dir "+toDirPath+" successfully.");
    }
    public void createOkFile(String file,String toDirPath) throws IOException{
        File toDir=new File(toDirPath);
        if(!toDir.exists()){
            toDir.mkdir();
        }
        File okFile=new File(file+GlobalParas.FILE_SUFFIX);
        if (new File(file).exists() && !new File(file).getAbsolutePath().endsWith(GlobalParas.FILE_SUFFIX) && !okFile.exists()){
            okFile.createNewFile();
        }
        LOG.info("create okfile "+new File(file).getAbsolutePath()+" to dir "+toDirPath+" successfully.");
    }
}
